#include "GameEngine.h"
#include <iostream>
#include <string>
#include <limits>
#include <boost/bind.hpp>

#include <boost/thread.hpp>

#include "network/GameServer.h"
#include "network/GameMessage.h"
#include "network/GameClient.h"
#include "network/GameObserver.h"
#include "NetworkListener.h"

using boost::asio::ip::tcp;

GameEngine::GameEngine(){

}
void GameEngine::update(){
  GameMessage e;
  e.m_login = game_client.get_login();
  e.m_type = GameMessage::POSITION_CHANGED;
  game_client.write(e);
}

void GameEngine::run_server_thread(unsigned short int port){
        try
        {

                tcp::endpoint endpoint(tcp::v4(), port);
                GameServer server(io_service_server, endpoint);
				io_service_server.run();            
        }
        catch (std::exception& e)
        {
                std::cerr << "Exception: " << e.what() << "\n";
        }
}

void GameEngine::run_server(unsigned short int port){
        boost::thread t(boost::bind(&GameEngine::run_server_thread, this,port));
}

void GameEngine::run_client(Player& player,std::string ip,unsigned short int port){
        try
        {
                // IP et port de destination
                tcp::endpoint endpoint(boost::asio::ip::address::from_string(ip), port);

                // Création d'un client chat
                game_client.connect(io_service_client,endpoint, player);


                // Lancement du service principal dans un thread. Il continue tant qu'il reste des
                // opérations asynchrones en cours (il ne s'arrête donc jamais)
                boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service_client));



        }
        catch (std::exception& e)
        {
                std::cerr << "Exception: " << e.what() << "\n";
        }

}

void GameEngine::add_network_listener(NetworkListener* listener){
    game_client.add_observer(listener);
}

GameEngine::~GameEngine(){

}
